const initialState = {
  items: [],  //[{id: 商品id, num: 数量}]
  checkStatus: null,  //null/success/fail
};

//拆分items的reduce
const items = (state, action) => {
  const { type } = action;
  switch (type) {
    case "ADD_TO_CART":
      //判断购物车内是否已经有这种商品
      //存在: 让购物车数量加1
      //不存在: 在购物车中添加
      const productId = action.product.id;
      const product = state.find(i => i.id === productId);
      if (!product) {
        return [...state, { id: productId, num: 1 }]
      } else {
        product.num++;
        return [...state];
      }
    case "SET_ITEMS":
      return action.product;
    default:
      return state;
  }
}

export default (state = initialState, action) => {

  switch (action.type) {
    case "SET_CHECKOUT_STATUS":
      return {
        ...state,
        checkStatus: action.status
      }
    // case :
    //   break;
    default:
      return {
        items: items(state.items, action),
        checkStatus: state.checkStatus,
      }
  };


}